package com.wyp168.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @ClassName CASByAtumicStampRefrenceObjectMethod
 * @Description TODO
 * @Author wyp168
 * @Date 2022/9/17 21:59
 */
public class CASByAtomicStampReferenceObjectMethod {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(100);

        AtomicStampedReference integerReference = new AtomicStampedReference<>(100, 1);

        new Thread(() -> {
            boolean firstOperationResult = integerReference.compareAndSet(100, 1115,  integerReference.getStamp(), integerReference.getStamp() - 1);
            System.out.println(Thread.currentThread().getName() + "\t 第一次操作 --->" + firstOperationResult + "====> " + integerReference.getReference().toString() + "\t" + integerReference.getStamp());
            try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) {e.printStackTrace();}
            boolean secondOperationResult = integerReference.compareAndSet(1115, 1234,  integerReference.getStamp(), integerReference.getStamp() - 1);
            System.out.println(Thread.currentThread().getName() + "\t 第二次操作 --->" + secondOperationResult + "====> " + integerReference.getReference().toString() + "\t" + integerReference.getStamp());
        }, "A").start();

//        new Thread(() -> {
//            try {
//                TimeUnit.MILLISECONDS.sleep(500);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            boolean firstOperationResult = integerReference.compareAndSet(1115, 9999,  integerReference.getStamp(), integerReference.getStamp() + 1);
//            System.out.println(Thread.currentThread().getName() + "\t 第一次操作 --->" + firstOperationResult + "====> " + integerReference.getReference().toString() + "\t" + integerReference.getStamp());
//            //线程沉睡两秒
//            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) {e.printStackTrace();}
//            boolean secondOperationResult = integerReference.compareAndSet(9999, 1115,  integerReference.getStamp(), integerReference.getStamp() + 1);
//            System.out.println(Thread.currentThread().getName() + "\t 第二次操作 --->" + secondOperationResult + "====> " + integerReference.getReference().toString() + "\t" + integerReference.getStamp());
//        }, "B").start();
    }
}
